import {useImmerState} from '../../hooks/useImmerState';
import useGlobal from '../../hooks/useGlobal';
import * as subjectApi from '../../apis/subject';
import useDidMount from '../../hooks/useDidMount';
import {message} from 'antd';

const useSubjectModel = () => {

  const {state: globalState} = useGlobal();
  const [state, setState] = useImmerState({
    list: []
  });

  const getSubjectList = async () => {
    const res = await subjectApi.list(globalState.login?.token);
    if (res.data.code === 1) {
      setState(draft => {
        draft.list = res.data.data.list;
      });
    }
  };

  const addSubject = async (subject) => {
    const res = await subjectApi.add(globalState.login?.token, subject);
    if (res.data.code === 1) {
      setState(draft => {
        draft.list.push(res.data.data.list);
      });
      message.success('添加成功');
    }
  };

  const delSubject = async (subject) => {
    const res = await subjectApi.del(globalState.login?.token, subject.id);
    if (res.data.code === 1) {
      setState(draft => {
        draft.list = draft.list.filter(item => item.id !== subject.id);
      });
    }
  };

  const updateSubject = async (subject) => {
    const res = await subjectApi.update(globalState.login?.token, subject.id, subject);
    if (res.data.code === 1) {
      setState(draft => {
        draft.list[subject.index] = subject;
      });
      message.success('修改成功');
    }
  };

  useDidMount(() => {
    getSubjectList();
  });

  const effect = {
    getSubjectList,
    addSubject,
    delSubject,
    updateSubject
  };

  return {
    state,
    effect
  };
};

export default useSubjectModel;